package com.ch.clinking.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.Utils.TimeUtil;
import com.ch.clinking.adapter.Order.AddOrderAdapter;
import com.ch.clinking.bean.MerchandiseDto;
import com.ch.clinking.bean.Order;
import com.ch.clinking.bean.OrderInfo;
import com.ch.clinking.databinding.ActivityAddOrderBinding;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddOrderActivity extends AppCompatActivity {

    private ActivityAddOrderBinding binding;
    private MerchandiseDto merchandise;
    private List<OrderInfo> orderInfoList;
    private AddOrderAdapter addOrderAdapter;
    private RecyclerView.LayoutManager layoutManager;

    private Order order;

    private ClinkingApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityAddOrderBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置状态栏图标为深色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        app = ClinkingApplication.getInstance();

        Intent intent = getIntent();
        String skcId = (String) intent.getSerializableExtra("skcId");
        // 通过SKC获取该商品信息
        if (skcId != null) {

            showLoading();

            // 获取订单TAG列表
            HashMap<String, String> mer = new HashMap<>();
            mer.put("skcId", skcId);

            OkHttpUtil.getInstance().doPostForm("/mer/selectMerBySkcId", new DoCallBack() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onSuccess(String result) {
                    Log.d("selectMerBySkcId", "result:"+result);

                    merchandise = new Gson().fromJson(result, MerchandiseDto.class);

                    orderInfoList = new ArrayList<>();
                    setMerMap(merchandise);
                    addOrderAdapter = new AddOrderAdapter(AddOrderActivity.this, orderInfoList);
                    binding.addOrderSkuStockList.setAdapter(addOrderAdapter);
                    layoutManager = new LinearLayoutManager(AddOrderActivity.this);
                    binding.addOrderSkuStockList.setLayoutManager(layoutManager);
                    binding.addOrderMerTitle.setText(merchandise.getTitle());
                    binding.addOrderMerSkcId.setText(merchandise.getSkcId());
                    binding.addOrderAddSKCProductNum.setText(merchandise.getProductNumber());

                    // 设置默认占位图片
                    Glide.with(AddOrderActivity.this)
                            .load(R.drawable.appicon)
                            .into(binding.addOrderMerImg);

                    // 加载图片
                    Glide.with(AddOrderActivity.this)
                            .load(OkHttpUtil.getInstance().getIMG_URL() + merchandise.getFirstImage())
                            .placeholder(R.drawable.appicon)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略：缓存原始图片和转换后的图片
                            .thumbnail(0.5f)  // 缩略图大小
                            .error(R.drawable.appicon)
                            .into(binding.addOrderMerImg);

                    hideLoading();
                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(AddOrderActivity.this, "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                    hideLoading();
                }
            }, mer);


        }


        binding.addOrderStockCommit.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View view) {

                showLoading();

                String shopId = app.shopList.get(app.shopPosition).getShopId();

                //初始化订单
                order = new Order(shopId, TimeUtil.getStringFormatTime()+shopId.substring(shopId.length() - 4),TimeUtil.getFormatTime(), merchandise.getSkcId());


                int totalNum = 0;

                // 获取RecyclerView中各项的内容，设置各尺码下单数量
                for (int i = 0; i < addOrderAdapter.getItemCount(); i++) {
                    setOrderSkuNum(addOrderAdapter.orderInfoList.get(i).getTitle(), addOrderAdapter.orderInfoList.get(i).getFinalNum());
                    totalNum += addOrderAdapter.orderInfoList.get(i).getFinalNum();
                }

                if (totalNum <= 0) {
                    Toast.makeText(AddOrderActivity.this, "下单总数不可小于零", Toast.LENGTH_SHORT).show();
                    hideLoading();
                    return;
                }

                String orderString = new Gson().toJson(order);

                Log.d("orderString", orderString);

                OkHttpUtil.getInstance().doPostJson("/order/updateOrder", new DoCallBack() {
                    @Override
                    public void onSuccess(String result) {

                        Log.d("updateOrder", result);
                        hideLoading();


                        Intent resultIntent = new Intent();
                        resultIntent.putExtra("makeOrderFinished", "True");
                        resultIntent.putExtra("updatedMerchandise", merchandise.getSkcId());
                        setResult(Activity.RESULT_OK, resultIntent);

                        AddOrderActivity.this.finish(); // 关闭当前Activity

                    }

                    @Override
                    public void onError(Exception e) {
                        Log.d("updateOrder", "error");
                        Toast.makeText(AddOrderActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                    }
                }, orderString);

            }
        });

        binding.addOrderBatchStockSetting.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                // 创建Dialog
                AlertDialog.Builder builder = new AlertDialog.Builder(AddOrderActivity.this);
                builder.setTitle("输入下单数量");

                // 使用LayoutInflater加载自定义布局
                LayoutInflater inflater = getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.dialog_add_order_batch_number, null);
                builder.setView(dialogView);

                // 获取输入框和按钮
                final EditText inputNumber = dialogView.findViewById(R.id.dialog_add_order_batch_number_input_number);
                Button btnCancel = dialogView.findViewById(R.id.dialog_add_order_batch_BtnCancel);
                Button btnConfirm = dialogView.findViewById(R.id.dialog_add_order_batch_BtnConfirm);

                // 创建并显示Dialog
                AlertDialog dialog = builder.create();
                dialog.show();

                // 设置取消按钮点击事件
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                // 设置确认按钮点击事件
                btnConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String input = inputNumber.getText().toString();
                        if (!input.isEmpty()) {
                            int number = Integer.parseInt(input);
                            // 处理输入的数字
                            handleInputNumber(number);
                            dialog.dismiss();
                        } else {
                            Toast.makeText(AddOrderActivity.this, "请输入一个有效的数字", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });

    }

    // 处理输入的数字
    @SuppressLint("NotifyDataSetChanged")
    private void handleInputNumber(int number) {

        // 更改RecyclerView中各项的内容，设置FinalNum数量
        for (OrderInfo orderInfo : addOrderAdapter.orderInfoList) {
            orderInfo.setFinalNum(number);
        }

        addOrderAdapter.notifyDataSetChanged();
        // 在这里处理输入的数字，例如更新订单数量
//        Toast.makeText(this, "输入的数字是: " + number, Toast.LENGTH_SHORT).show();
    }

    private void setOrderSkuNum(String title, int stock) {
        if (title.equals("XXS")) {
            order.setXXS(Math.max(stock, 0));
            order.setActivate_XXS(1);
        }
        if (title.equals("XS")) {
            order.setXS(Math.max(stock, 0));
            order.setActivate_XS(1);
        }
        if (title.equals("S")) {
            order.setS(Math.max(stock, 0));
            order.setActivate_S(1);
        }
        if (title.equals("M")) {
            order.setM(Math.max(stock, 0));
            order.setActivate_M(1);
        }
        if (title.equals("L")) {
            order.setL(Math.max(stock, 0));
            order.setActivate_L(1);
        }
        if (title.equals("XL")) {
            order.setXL(Math.max(stock, 0));
            order.setActivate_XL(1);
        }
        if (title.equals("XXL")) {
            order.setXXL(Math.max(stock, 0));
            order.setActivate_XXL(1);
        }
        if (title.equals("0XL")) {
            order.setPlus_0XL(Math.max(stock, 0));
            order.setActivate_Plus_0XL(1);
        }
        if (title.equals("1XL")) {
            order.setPlus_1XL(Math.max(stock, 0));
            order.setActivate_Plus_1XL(1);
        }
        if (title.equals("2XL")) {
            order.setPlus_2XL(Math.max(stock, 0));
            order.setActivate_Plus_2XL(1);
        }
        if (title.equals("3XL")) {
            order.setPlus_3XL(Math.max(stock, 0));
            order.setActivate_Plus_3XL(1);
        }
        if (title.equals("4XL")) {
            order.setPlus_4XL(Math.max(stock, 0));
            order.setActivate_Plus_4XL(1);
        }
        if (title.equals("5XL")) {
            order.setPlus_5XL(Math.max(stock, 0));
            order.setActivate_Plus_5XL(1);
        }
        if (title.equals("6XL")) {
            order.setPlus_6XL(Math.max(stock, 0));
            order.setActivate_Plus_6XL(1);
        }
    }


    private void setMerMap(MerchandiseDto merchandise) {
        if (merchandise.isActivate_XXS()) {
            OrderInfo orderInfo = new OrderInfo("XXS", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_XS()) {
            OrderInfo orderInfo = new OrderInfo("XS", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_S()) {
            OrderInfo orderInfo = new OrderInfo("S", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_M()) {
            OrderInfo orderInfo = new OrderInfo("M", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_L()) {
            OrderInfo orderInfo = new OrderInfo("L", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_XL()) {
            OrderInfo orderInfo = new OrderInfo("XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_XXL()) {
            OrderInfo orderInfo = new OrderInfo("XXL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_0XL()) {
            OrderInfo orderInfo = new OrderInfo("0XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_1XL()) {
            OrderInfo orderInfo = new OrderInfo("1XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_2XL()) {
            OrderInfo orderInfo = new OrderInfo("2XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_3XL()) {
            OrderInfo orderInfo = new OrderInfo("3XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_4XL()) {
            OrderInfo orderInfo = new OrderInfo("4XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_5XL()) {
            OrderInfo orderInfo = new OrderInfo("5XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
        if (merchandise.isActivate_Plus_6XL()) {
            OrderInfo orderInfo = new OrderInfo("6XL", merchandise.getFirstImage());
            orderInfoList.add(orderInfo);
        }
    }

    private void showLoading() {
        binding.AddOrderEditMerStockLoadingProgressBar.setVisibility(View.VISIBLE);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    private void hideLoading() {
        binding.AddOrderEditMerStockLoadingProgressBar.setVisibility(View.GONE);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

}